package com.ruicar.afs.cloud.channel.grade.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.channel.common.feign.ChannelUseCaseService;
import com.ruicar.afs.cloud.channel.common.until.ChannelConfig;
import com.ruicar.afs.cloud.channel.grade.ao.GradeModelAO;
import com.ruicar.afs.cloud.channel.grade.condition.GradeModelResultCondition;
import com.ruicar.afs.cloud.channel.grade.constant.Constants;
import com.ruicar.afs.cloud.channel.grade.dto.ChannelRiskInfoTempDTO;
import com.ruicar.afs.cloud.channel.grade.dto.GradeModelResultSubDTO;
import com.ruicar.afs.cloud.channel.grade.dto.GradeModelResultSubDtlDTO;
import com.ruicar.afs.cloud.channel.grade.dto.Level2ElementsDTO;
import com.ruicar.afs.cloud.channel.grade.entity.*;
import com.ruicar.afs.cloud.channel.grade.service.*;
import com.ruicar.afs.cloud.channel.grade.utils.DicUtils;
import com.ruicar.afs.cloud.channel.online.condition.ArchivesLogInfoCondition;
import com.ruicar.afs.cloud.channel.online.entity.ChannelBaseInfoTemp;
import com.ruicar.afs.cloud.channel.online.entity.ChannelRiskInfoTemp;
import com.ruicar.afs.cloud.channel.online.service.ChannelArchivesInfoService;
import com.ruicar.afs.cloud.channel.online.service.ChannelOnlineService;
import com.ruicar.afs.cloud.channel.online.service.ChannelRiskInfoService;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.query.QueryCondition;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.components.datadicsync.DicHelper;
import com.ruicar.afs.cloud.components.datadicsync.dto.DicDataDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/grade/gradeModelResult")
@Api(value = "grade", description = "评级结果controller")
public class GradeModelResultController {
    private static final Logger logger = LoggerFactory.getLogger(GradeModelResultController.class);

    @Autowired
    private GradeModelResultService gradeModelResultService;
    @Autowired
    private GradeModelResultDtlService gradeModelResultDtlService;
    @Autowired
    private GradeModelElementService gradeModelElementService;
    @Autowired
    private GradeModelResultSubDtlService gradeModelResultSubDtlService;
    @Autowired
    private ChannelOnlineService channelOnlineService;
    @Autowired
    private ChannelRiskInfoService channelRiskInfoService;
    @Autowired
    private GradeModelResultModifyLogService gradeModelResultModifyLogService;
    @Autowired
    private GradeModelAO gradeModelAO;
    @Autowired
    private ChannelArchivesInfoService channelArchivesInfoService;

    private ChannelUseCaseService channelFeignService;
    private ChannelConfig channelConfig;


    @PostMapping("/queryGradeResult")
    @ApiOperation(value = "分页获取动态评级数据")
    public IResponse<IPage<JSONObject>> queryGradeResult(@RequestBody QueryCondition<GradeModelResultCondition> condition) {
        try {
            logger.info("queryGradeResult方法输入参数：---->" + JSONObject.toJSONString(condition));
            Page page = new Page(condition.getPageNumber(), condition.getPageSize());
            IPage<GradeModelResult> ipage = gradeModelResultService.page(page, Wrappers.<GradeModelResult>query().lambda()
                    .eq(GradeModelResult::getGradeType, Constants.GRADE_TYPE_BIGDATA)
                    .eq(GradeModelResult::getDelFlag, Constants.DEL_FLAG_NO)
                    .likeRight(StringUtils.isNotBlank(condition.getCondition().getGradeDateStr8()), GradeModelResult::getGradeDateStr8,
                            StringUtils.isBlank(condition.getCondition().getGradeDateStr8()) ? "" : condition.getCondition().getGradeDateStr8().substring(0, 8).replaceAll("-", ""))
                    .like(StringUtils.isNotBlank(condition.getCondition().getCustomerManager()), GradeModelResult::getCustomerManager, condition.getCondition().getCustomerManager())
                    .eq(StringUtils.isNotBlank(condition.getCondition().getModelValue()), GradeModelResult::getModelValue, condition.getCondition().getModelValue())
                    .eq(StringUtils.isNotBlank(condition.getCondition().getChannelCode()), GradeModelResult::getChannelCode, condition.getCondition().getChannelCode())
                    .like(StringUtils.isNotBlank(condition.getCondition().getChannelFullName()), GradeModelResult::getChannelFullName, condition.getCondition().getChannelFullName())
                    .eq(StringUtils.isNotBlank(condition.getCondition().getBusinessType()), GradeModelResult::getBusinessType, condition.getCondition().getBusinessType())
                    .eq(StringUtils.isNotBlank(condition.getCondition().getChannelBelong()), GradeModelResult::getChannelBelongDtl, condition.getCondition().getChannelBelong())
                    .between(condition.getCondition().getScoreStart() != null && condition.getCondition().getScoreEnd() != null, GradeModelResult::getModelSocre,
                            condition.getCondition().getScoreStart(), condition.getCondition().getScoreEnd()));

            List<GradeModelResult> sourceList = ipage.getRecords();
            List<JSONObject> jsonObjectList = new ArrayList<JSONObject>();
            if (CollectionUtils.isNotEmpty(sourceList)) {
                //由于指标种类可能动态增加，导致页面增加列，因此转换为jsonObject对象返回
                for (GradeModelResult gradeModelResult : sourceList) {
                    //把gradeModelResult转换为jsonObject对象，再增加指标字段
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("resultId", gradeModelResult.getId().toString());
                    jsonObject.put("customerManager", gradeModelResult.getCustomerManager());
                    jsonObject.put("channelCode", gradeModelResult.getChannelCode());
                    jsonObject.put("channelFullName", gradeModelResult.getChannelFullName());
                    jsonObject.put("businessType", gradeModelResult.getBusinessType());
                    jsonObject.put("lastModelValue", gradeModelResult.getLastModelValue());
                    jsonObject.put("modelValue", gradeModelResult.getModelValue());
                    jsonObject.put("modelSocre", gradeModelResult.getModelSocre());
                    jsonObject.put("gradeDateStr8", gradeModelResult.getGradeDateStr8());
                    jsonObject.put("modelCode", gradeModelResult.getModelCode());
                    //动态拼装一级指标汇总分数
                    List<GradeModelResultSubDtl> gradeModelResultSubDtls = gradeModelResultSubDtlService.list(Wrappers.<GradeModelResultSubDtl>query().lambda()
                            .eq(GradeModelResultSubDtl::getGrantModelRstId, gradeModelResult.getId()));
                    if (CollectionUtils.isNotEmpty(gradeModelResultSubDtls)) {
                        for (GradeModelResultSubDtl gradeModelResultSubDtl : gradeModelResultSubDtls) {
                            //modelCode和elementNo唯一确定一条指标GradeModelElement
                            GradeModelElement element = gradeModelElementService.getOne(Wrappers.<GradeModelElement>query().lambda()
                                    .eq(GradeModelElement::getModelCode, gradeModelResult.getModelCode())
                                    .eq(GradeModelElement::getElementNo, gradeModelResultSubDtl.getGradeNo()));
                            if (element != null && StringUtils.isNotBlank(element.getElementCode())) {
                                //一级指标汇总分数、id、一级指标调整分数
                                jsonObject.put(element.getElementCode(), gradeModelResultSubDtl.getScore());
                                jsonObject.put(element.getElementCode() + "_subId", gradeModelResultSubDtl.getId().toString());
                                jsonObject.put(element.getElementCode() + "_addScore", gradeModelResultSubDtl.getAddScore());

                                //动态拼装二级详细指标输入输出详细
                                List<GradeModelResultDtl> gradeModelResultDtls = gradeModelResultDtlService.list(Wrappers.<GradeModelResultDtl>query().lambda()
                                        .eq(GradeModelResultDtl::getGrantModelRstId, gradeModelResult.getId())
                                        .eq(GradeModelResultDtl::getSubId, gradeModelResultSubDtl.getId()));
                                if (CollectionUtils.isNotEmpty(gradeModelResultDtls)) {
                                    for (GradeModelResultDtl gradeModelResultDtl : gradeModelResultDtls) {
                                        //modelCode和elementNo唯一确定一条指标GradeModelElement
                                        GradeModelElement element1 = gradeModelElementService.getOne(Wrappers.<GradeModelElement>query().lambda()
                                                .eq(GradeModelElement::getModelCode, gradeModelResult.getModelCode())
                                                .eq(GradeModelElement::getElementNo, gradeModelResultDtl.getGradeNo()));
                                        if (element1 != null && StringUtils.isNotBlank(element1.getElementCode())) {
                                            jsonObject.put(element1.getElementCode(), gradeModelResultDtl.getDtlStr() == null ? "" : gradeModelResultDtl.getDtlStr());//详细指标输入参数
                                            jsonObject.put(element1.getElementCode() + "Value", gradeModelResultDtl.getDtlValue() == null ? "" : gradeModelResultDtl.getDtlValue());//详细指标计算输出结果
                                        }
                                    }
                                }
                            }
                        }
                    }
                    jsonObjectList.add(jsonObject);
                }
            }

            //重新拼装分页对象返回
            IPage<JSONObject> returnPage = new Page<JSONObject>();
            returnPage.setRecords(jsonObjectList);
            returnPage.setCurrent(ipage.getCurrent());
            returnPage.setTotal(ipage.getTotal());
            returnPage.setPages(ipage.getPages());
            returnPage.setSize(ipage.getSize());
            return IResponse.success(returnPage);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return IResponse.fail("查询失败，请联系管理员！");
        }
    }

    @PostMapping("/exportGradeResult")
    @ApiOperation(value = "导出动态评级数据")
    public IResponse<List<JSONObject>> exportGradeResult(@RequestBody QueryCondition<GradeModelResultCondition> condition) {
        try {
            logger.info("exportGradeResult方法输入参数：---->" + JSONObject.toJSONString(condition));
            List<GradeModelResult> sourceList = gradeModelResultService.list(Wrappers.<GradeModelResult>query().lambda()
                    .eq(GradeModelResult::getGradeType, Constants.GRADE_TYPE_BIGDATA)
                    .eq(StringUtils.isNotBlank(condition.getCondition().getGradeDateStr8()), GradeModelResult::getGradeDateStr8, condition.getCondition().getGradeDateStr8())
                    .eq(StringUtils.isNotBlank(condition.getCondition().getCustomerManager()), GradeModelResult::getCustomerManager, condition.getCondition().getCustomerManager())
                    .eq(StringUtils.isNotBlank(condition.getCondition().getModelValue()), GradeModelResult::getModelValue, condition.getCondition().getModelValue())
                    .eq(StringUtils.isNotBlank(condition.getCondition().getChannelCode()), GradeModelResult::getChannelCode, condition.getCondition().getChannelCode())
                    .eq(StringUtils.isNotBlank(condition.getCondition().getChannelFullName()), GradeModelResult::getChannelFullName, condition.getCondition().getChannelFullName())
                    .eq(StringUtils.isNotBlank(condition.getCondition().getBusinessType()), GradeModelResult::getBusinessType, condition.getCondition().getBusinessType())
                    .eq(StringUtils.isNotBlank(condition.getCondition().getChannelBelong()), GradeModelResult::getChannelBelongDtl, condition.getCondition().getChannelBelong())
                    .between(condition.getCondition().getScoreStart() != null && condition.getCondition().getScoreEnd() != null, GradeModelResult::getModelSocre,
                            condition.getCondition().getScoreStart(), condition.getCondition().getScoreEnd()));

            List<JSONObject> jsonObjectList = new ArrayList<JSONObject>();
            if (CollectionUtils.isNotEmpty(sourceList)) {
                //由于指标种类可能动态增加，导致页面增加列，因此转换为jsonObject对象返回
                for (GradeModelResult gradeModelResult : sourceList) {
                    //把gradeModelResult转换为jsonObject对象，再增加指标字段
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("resultId", gradeModelResult.getId().toString());
                    jsonObject.put("customerManager", gradeModelResult.getCustomerManager());
                    jsonObject.put("channelCode", gradeModelResult.getChannelCode());
                    jsonObject.put("channelFullName", gradeModelResult.getChannelFullName());
                    jsonObject.put("bussinessType", gradeModelResult.getBusinessType());
                    jsonObject.put("lastModelValue", gradeModelResult.getLastModelValue());
                    jsonObject.put("modelValue", gradeModelResult.getModelValue());
                    jsonObject.put("modelSocre", gradeModelResult.getModelSocre());
                    jsonObject.put("gradeDateStr8", gradeModelResult.getGradeDateStr8());
                    jsonObject.put("modelCode", gradeModelResult.getModelCode());
                    //动态拼装一级指标汇总分数
                    List<GradeModelResultSubDtl> gradeModelResultSubDtls = gradeModelResultSubDtlService.list(Wrappers.<GradeModelResultSubDtl>query().lambda()
                            .eq(GradeModelResultSubDtl::getGrantModelRstId, gradeModelResult.getId()));
                    if (CollectionUtils.isNotEmpty(gradeModelResultSubDtls)) {
                        for (GradeModelResultSubDtl gradeModelResultSubDtl : gradeModelResultSubDtls) {
                            //modelCode和elementNo唯一确定一条指标GradeModelElement
                            GradeModelElement element = gradeModelElementService.getOne(Wrappers.<GradeModelElement>query().lambda()
                                    .eq(GradeModelElement::getModelCode, gradeModelResult.getModelCode())
                                    .eq(GradeModelElement::getElementNo, gradeModelResultSubDtl.getGradeNo()));
                            if (element != null && StringUtils.isNotBlank(element.getElementCode())) {
                                //一级指标汇总分数、id、一级指标调整分数
                                jsonObject.put(element.getElementCode(), gradeModelResultSubDtl.getScore());
                                jsonObject.put(element.getElementCode() + "_subId", gradeModelResultSubDtl.getId().toString());
                                jsonObject.put(element.getElementCode() + "_addScore", gradeModelResultSubDtl.getAddScore());

                                //动态拼装二级详细指标输入输出详细
                                List<GradeModelResultDtl> gradeModelResultDtls = gradeModelResultDtlService.list(Wrappers.<GradeModelResultDtl>query().lambda()
                                        .eq(GradeModelResultDtl::getGrantModelRstId, gradeModelResult.getId())
                                        .eq(GradeModelResultDtl::getSubId, gradeModelResultSubDtl.getId()));
                                if (CollectionUtils.isNotEmpty(gradeModelResultDtls)) {
                                    for (GradeModelResultDtl gradeModelResultDtl : gradeModelResultDtls) {
                                        //modelCode和elementNo唯一确定一条指标GradeModelElement
                                        GradeModelElement element1 = gradeModelElementService.getOne(Wrappers.<GradeModelElement>query().lambda()
                                                .eq(GradeModelElement::getModelCode, gradeModelResult.getModelCode())
                                                .eq(GradeModelElement::getElementNo, gradeModelResultDtl.getGradeNo()));
                                        if (element1 != null && StringUtils.isNotBlank(element1.getElementCode())) {
                                            jsonObject.put(element1.getElementCode(), gradeModelResultDtl.getDtlStr() == null ? "" : gradeModelResultDtl.getDtlStr());//详细指标输入参数
                                            jsonObject.put(element1.getElementCode() + "Value", gradeModelResultDtl.getDtlValue() == null ? "" : gradeModelResultDtl.getDtlValue());//详细指标计算输出结果
                                        }
                                    }
                                }
                            }
                        }
                    }
                    jsonObjectList.add(jsonObject);
                }
            }
            //重新拼装分页对象返回
            return IResponse.success("导出成功").setData(jsonObjectList);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return IResponse.fail("导出失败，请联系管理员！");
        }
    }

    @Transactional
    @PostMapping("/saveChangeResult")
    @ApiOperation(value = "保存手工调整后的一级指标汇总分,联动修改总分和评级")
    public IResponse<Boolean> saveChangeResult(@RequestBody GradeModelResultSubDTO dto) throws Exception {
        if (dto == null || CollectionUtils.isEmpty(dto.getDtoList())) {
            return IResponse.fail("输入参数不能为空！");
        }
        logger.info("saveChangeResult方法输入参数：---->" + JSONObject.toJSONString(dto));

        //模型评估结果
        BigDecimal modelSocre = dto.getModelScore();
        Long resultId = dto.getResultId();
        try {
            //改模型总分数、联动评级修改
            GradeModelResult gradeModelResult = gradeModelResultService.getOne(Wrappers.<GradeModelResult>query().lambda().eq(GradeModelResult::getId, resultId));
            if (gradeModelResult != null) {
                BigDecimal beforeChangeScore = gradeModelResult.getModelSocre();
                String beforeChangeGrade = gradeModelResult.getModelValue();
                BigDecimal afterChangeScore = modelSocre;
                gradeModelResult.setModelSocre(afterChangeScore);
                String afterChangeGrade = gradeModelAO.getGradeByScore(afterChangeScore);
                gradeModelResult.setModelValue(afterChangeGrade);
                gradeModelResult.setRemark("用户" + SecurityUtils.getUser().getId() + "于" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss") + "修改评分");
                gradeModelResultService.updateById(gradeModelResult);

                //保存模型总分修改历史
                GradeModelResultModifyLog log = new GradeModelResultModifyLog();
                log.setTableName("grade_model_result");
                log.setTableId(gradeModelResult.getId());
                log.setBeforeScore(beforeChangeScore);
                log.setAfterScore(afterChangeScore);
                log.setBeforeGrade(beforeChangeGrade);
                log.setAfterGrade(afterChangeGrade);
                log.setUpdateUser(SecurityUtils.getUser().getId());
                log.setUpdateDate(new Date());
                gradeModelResultModifyLogService.save(log);

                //修改一级、二级分保存
                List<GradeModelResultSubDtlDTO> gradeModelResultSubDtlDTOS = dto.getDtoList();
                if (CollectionUtils.isNotEmpty(gradeModelResultSubDtlDTOS)) {
                    for (GradeModelResultSubDtlDTO gradeModelResultSubDtlDTO : gradeModelResultSubDtlDTOS) {
                        if (gradeModelResultSubDtlDTO != null) {
                            GradeModelResultSubDtl gradeModelResultSubDtl = gradeModelResultSubDtlService.getOne(Wrappers.<GradeModelResultSubDtl>query().lambda()
                                    .eq(GradeModelResultSubDtl::getId, gradeModelResultSubDtlDTO.getSubId()));
                            if (gradeModelResultSubDtl != null) {
                                BigDecimal beforeScore = gradeModelResultSubDtl.getScore();
                                BigDecimal beforeAddScore = gradeModelResultSubDtl.getAddScore();
                                //一级分数和调整分保存
                                gradeModelResultSubDtl.setScore(gradeModelResultSubDtlDTO.getScore());
                                gradeModelResultSubDtl.setAddScore(gradeModelResultSubDtlDTO.getAddScore());
                                gradeModelResultSubDtlService.updateById(gradeModelResultSubDtl);

                                //保存一级分修改历史
                                GradeModelResultModifyLog log1 = new GradeModelResultModifyLog();
                                log1.setTableName("grade_model_result_sub_dtl");
                                log1.setTableId(gradeModelResultSubDtl.getId());
                                log1.setBeforeScore(beforeScore);
                                log1.setBeforeAddScore(beforeAddScore);
                                log1.setAfterScore(gradeModelResultSubDtlDTO.getScore());
                                log1.setAfterAddScore(gradeModelResultSubDtlDTO.getAddScore());
                                log1.setBeforeGrade(null);
                                log1.setAfterGrade(null);
                                log1.setUpdateUser(SecurityUtils.getUser().getId());
                                log1.setUpdateDate(new Date());
                                gradeModelResultModifyLogService.save(log1);

                                List<Level2ElementsDTO> level2Elements = gradeModelResultSubDtlDTO.getLevel2Elements();
                                if (CollectionUtils.isNotEmpty(level2Elements)) {
                                    // 保存二级定性指标输入值和经过权重计算的结果
                                    for (Level2ElementsDTO level2ElementsDTO : level2Elements) {
                                        GradeModelResultDtl gradeModelResultDtl = gradeModelResultDtlService.getOne(Wrappers.<GradeModelResultDtl>query().lambda()
                                                .eq(GradeModelResultDtl::getGrantModelRstId, resultId)
                                                .eq(GradeModelResultDtl::getGradeNo, level2ElementsDTO.getElementNo()));
                                        String beforeDtlStr2 = "";
                                        BigDecimal beforeScore2 = BigDecimal.ZERO;
                                        //若是新增定性指标
                                        if (gradeModelResultDtl == null) {
                                            gradeModelResultDtl = new GradeModelResultDtl();
                                            gradeModelResultDtl.setDtlStr(level2ElementsDTO.getElementStr());
                                            gradeModelResultDtl.setDtlValue(level2ElementsDTO.getElementValue());
                                            gradeModelResultDtl.setGradeNo(level2ElementsDTO.getElementNo());
                                            gradeModelResultDtl.setSubId(gradeModelResultSubDtl.getId());
                                            gradeModelResultDtl.setGrantModelRstId(resultId);

                                            gradeModelResultDtlService.save(gradeModelResultDtl);
                                        } else {
                                            beforeDtlStr2 = gradeModelResultDtl.getDtlStr();
                                            beforeScore2 = gradeModelResultDtl.getDtlValue();
                                            //若是再次修改定性指标
                                            gradeModelResultDtl.setDtlStr(level2ElementsDTO.getElementStr());
                                            gradeModelResultDtl.setDtlValue(level2ElementsDTO.getElementValue());

                                            gradeModelResultDtlService.updateById(gradeModelResultDtl);
                                        }
                                        //保存二级定性指标修改历史
                                        GradeModelResultModifyLog log2 = new GradeModelResultModifyLog();
                                        log2.setTableName("grade_model_result_dtl");
                                        log2.setTableId(gradeModelResultSubDtl.getId());
                                        log2.setBeforeScore(beforeScore2);
                                        log2.setBeforeStr(beforeDtlStr2);
                                        log2.setAfterScore(level2ElementsDTO.getElementValue());
                                        log2.setBeforeGrade(null);
                                        log2.setAfterGrade(null);
                                        log2.setUpdateUser(SecurityUtils.getUser().getId());
                                        log2.setUpdateDate(new Date());
                                        gradeModelResultModifyLogService.save(log2);
                                    }
                                }
                            } else {
                                return IResponse.fail("数据不存在!");
                            }
                        }
                    }
                }
            } else {
                return IResponse.fail("数据不存在!");
            }
            return IResponse.success("保存成功！");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            //手动开启事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return IResponse.fail("保存失败，请联系管理员！");
        }
    }

    @Transactional
    @PostMapping("/apply")
    @ApiOperation(value = "评分结果修改后应用,批量接口")
    public IResponse<Boolean> apply(@RequestBody ChannelRiskInfoTempDTO dto) throws Exception {
        if (dto == null || dto.getResultId() == null || dto.getResultId().length == 0) {
            throw new Exception("必传参数不能为空");
        }
        logger.info("apply方法输入参数：---->" + JSONObject.toJSONString(dto));
        try {
            Map<String, List<DicDataDto>> dataDicMap = DicHelper.getDicMaps("businessType");
            //批量应用
            Long[] resultId = dto.getResultId();
            for (int i = 0; i < resultId.length; i++) {
                GradeModelResult gradeModelResult = gradeModelResultService.getOne(Wrappers.<GradeModelResult>query().lambda()
                        .eq(resultId[i] != null, GradeModelResult::getId, resultId[i]));
                if (gradeModelResult != null) {
                    ChannelBaseInfoTemp channelBaseInfoTemp = channelOnlineService.getOne(Wrappers.<ChannelBaseInfoTemp>query().lambda()
                            .eq(ChannelBaseInfoTemp::getChannelCode, gradeModelResult.getChannelCode()));
                    if (channelBaseInfoTemp != null) {
                        ChannelRiskInfoTemp channelRiskInfoTemp = channelRiskInfoService.getOne(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                                .eq(ChannelRiskInfoTemp::getChannelId, channelBaseInfoTemp.getId())
                                .eq(ChannelRiskInfoTemp::getBusinessType, gradeModelResult.getBusinessType()));
                        if (channelRiskInfoTemp != null) {
                            //和数据字典转换
                            String gradeTitle = gradeModelResult.getModelValue();
                            String gradevalue = "";
                            Map<String, List<DicDataDto>> channelGradeDicMap = DicHelper.getDicMaps("channelGrade");
                            List<DicDataDto> list = channelGradeDicMap.get("channelGrade");
                            if (CollectionUtils.isNotEmpty(list)) {
                                for (DicDataDto dicDataDto : list) {
                                    if (dicDataDto.getTitle().equals(gradeTitle)) {
                                        gradevalue = dicDataDto.getValue();
                                        break;
                                    }
                                }
                            }

                            //先feign接口更新案件端渠道评级
                            Map<String, String> headers = new HashMap<>();
                            headers.put("clientId", channelConfig.getCaseClientId());
                            headers.put("clientSecret", channelConfig.getCaseClientSecret());

                            ChannelRiskInfoTemp riskInfo = new ChannelRiskInfoTemp();
                            riskInfo.setChannelId(channelBaseInfoTemp.getId());
                            riskInfo.setBusinessType(gradeModelResult.getBusinessType());
                            riskInfo.setChannelGrade(gradevalue);
                            IResponse response = channelFeignService.updateGrade(riskInfo, headers);
                            //feign接口调用成功的情况
                            if (response != null && CommonConstants.SUCCESS.equals(response.getCode())) {
                                //保存渠道端归档日志
                                ArchivesLogInfoCondition condition = new ArchivesLogInfoCondition();
                                condition.setChannelId(channelBaseInfoTemp.getId());
                                String businessTypeName = DicUtils.translate(gradeModelResult.getBusinessType(), dataDicMap);
                                condition.setEventName(businessTypeName + "渠道评级更新");
                                condition.setDescription(businessTypeName + "渠道评级更新为:" + gradeTitle);
                                channelArchivesInfoService.saveUpdateGradeArchivesInfo(condition);

                                //最后更新渠道端渠道评级
                                channelRiskInfoTemp.setChannelGrade(gradevalue);
                                channelRiskInfoService.updateById(channelRiskInfoTemp);
                            } else {
                                return IResponse.fail("应用失败，更新案件端评级失败，请联系管理员！");
                            }
                        } else {
                            return IResponse.fail("应用失败，未找到数据，请联系管理员！");
                        }
                    } else {
                        return IResponse.fail("应用失败，未找到数据，请联系管理员！");
                    }
                } else {
                    return IResponse.fail("应用失败，未找到数据，请联系管理员！");
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            //手动开启事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new AfsBaseException("应用失败！");
        }
        return IResponse.success("应用成功！");
    }
}
